package com.shengyin.ec.controller.cluster;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;

import com.shengyin.ec.controller.goods.GoodsForm;
import com.shengyin.ec.exception.ControllerException;
import com.shengyin.ec.model.entity.ChainCompany;
import com.shengyin.ec.model.entity.ClusterCompany;
import com.shengyin.ec.model.entity.Company;
import com.shengyin.ec.model.entity.Goods;
import com.shengyin.ec.model.entity.GoodsType;
import com.shengyin.ec.model.entity.Orders;
import com.shengyin.ec.service.cluster.ChainCompanyService;
import com.shengyin.ec.service.cluster.ClusterService;
import com.shengyin.ec.service.goods.GoodsService;
import com.shengyin.ec.service.goods.GoodsTypeService;
import com.shengyin.ec.service.order.OrderService;
import com.shengyin.ec.util.GetFirstLetterUtils;
import com.shengyin.ec.util.UploadFileUtil;

@Controller
public class ClusterController {

	@Autowired
	ClusterService clusterService;

	@Autowired
	Md5PasswordEncoder passwordEncoder;
	@Autowired
	GoodsTypeService goodsTypeService;

	@Autowired
	GoodsService goodsService;
	
	@Autowired
	OrderService orderService;
	
	@Autowired
	ChainCompanyService chainCompanyService;

	/*
	 * =========================================集群企业前台管理==========================
	 * ===================================================================================
	 */

	/*
	 * 申请成为集群企业
	 */

	@RequestMapping("/view/toClusterJoin.do")
	public String toClusterJoin(Model model) {

		return "/view/clusterJoin";
	}

	@RequestMapping("/clusterAdd.do")
	public String createClusterCompany(ClusterForm clusterForm,HttpServletRequest request,@RequestParam("filename1")MultipartFile filename1) {
		ClusterCompany clusterCompany = new ClusterCompany();

		try {
			clusterForm.setPwd(passwordEncoder.encodePassword("shengyin",
					clusterForm.getPwd()));
			BeanUtils.copyProperties(clusterCompany, clusterForm);
			clusterCompany.setCreateDate(new Date());
			String filePath = UploadFileUtil.Upload(request, filename1,"cluster/cetificate");
			clusterCompany.setCertificatesUpload(filePath);
			clusterService.createClusterCompany(clusterCompany);
			
			WebUtils.setSessionAttribute(request, "cluster", clusterCompany);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return "/view/cluster/clusterAddSuccess";
	}

	@RequestMapping("/toClusterList.do")
	public String toClusterList(Model model) {

		List<ClusterCompany> compnayList = clusterService.getClusterCompanyList();
		model.addAttribute("companyList", compnayList);

		return "/view/clusterCompanyList";

	}

	@RequestMapping("/toExit.do")
	public String exitCluster(HttpServletRequest request) {
		WebUtils.setSessionAttribute(request, "cluster", null);
		return "redirect:/default.jsp";
	}

	@RequestMapping("/viewCompanyGoods.do")
	public String viewCompany(@RequestParam("id") long id, Model model) {
		return "/view/clusterGoodsList";
	}

	/*
	 * =========================================集群企业后台管理分界线======================
	 * ===================================================
	 */
	/*
	 * 基本信息管理
	 */

	/*
	 * 到达基本信息管理
	 */
	@RequestMapping("/view/toClusterBaseInfo.do")
	public String toBaseInfo() {
		return "/view/cluster/clusterBaseInfo";
	}
	
    //提交集群基本信息的修改
	@RequestMapping("/view/clusterModify.do")
	public String clusterModify(ClusterForm clusterForm,@RequestParam("id") int id,HttpServletRequest request){
		
		ClusterCompany clusterCompany = clusterService.getClusterCompany(id);
		
		clusterCompany.setCompanyaddr(clusterForm.getCompanyaddr());
		clusterCompany.setCompanyarea(clusterForm.getCompanyarea());
		clusterCompany.setIndustry(clusterForm.getIndustry());
		clusterCompany.setPurposel(clusterForm.getPurposel());
		clusterCompany.setEmployees(clusterForm.getEmployees());
		clusterCompany.setNature(clusterForm.getNature());
		
		clusterService.modifyClusterCompany(clusterCompany);
		
		HttpSession session = request.getSession();
		session.setAttribute("cluster", clusterCompany);
		return "redirect:/view/toClusterBaseInfo.do";
	}
	
	@RequestMapping("/view/toClusterChangePsw.do")
	public String toPWDChange() {

		return "/view/cluster/clusterChangePsw";
	}
 
	@RequestMapping("/view/clusterChangePsw.do")
	public String clusterChangePsw(PswForm pswForm,HttpServletRequest request,Model model){
		
		HttpSession session = request.getSession();
		String error="";
		String success="";
		ClusterCompany clusterCompany = (ClusterCompany)session.getAttribute("cluster");
		String password1 = clusterCompany.getPwd();
		
		
		String password2 = passwordEncoder.encodePassword("shengyin",pswForm.getOldPsw());
		
		if(password1.equals(password2))
		{
			clusterCompany.setPwd(passwordEncoder.encodePassword("shengyin",pswForm.getNewPsw()));
			clusterService.modifyClusterCompany(clusterCompany);
			success="密码修改成功，下次登录时请用新密码";
			model.addAttribute("cluster", clusterCompany);
			System.out.print("success=="+success);
		}else
		{
			error = "密码输入错误";
		
		}
		
		model.addAttribute("error", error);
		model.addAttribute("success", success);
		
		return "/view/cluster/clusterChangePsw";
	}
	/**
	 * 商品管理
	 **/
	@RequestMapping("/view/toClusterGoodsList.do")
	public String toGoodsList(Model model, HttpServletRequest request) {
		int offset = 0;
		try {
			
			offset = Integer.valueOf(request.getParameter("pager.offset"));
		} catch (Exception ex) {
		}
		
		ClusterCompany clusterCompany =(ClusterCompany) WebUtils.getSessionAttribute(request, "cluster");
		if(clusterCompany==null)
			return "redirect:/view/login.jsp";
		
		List<Goods> goodsList =  clusterService.getClusterCompanyGoodsList(clusterCompany.getId(),offset, 10);
		
		Long maxSize = clusterService.getTotal(clusterCompany.getId());
		model.addAttribute("goodsList", goodsList);
		model.addAttribute("maxSize", maxSize);
		return "/view/cluster/clusterGoodsList";
	}

	@RequestMapping("/view/toClusterGoodsAdd.do")
	public String toGoodsAdd(Model model) {
		ArrayList<GoodsType> typeList = (ArrayList<GoodsType>) goodsTypeService
				.getGoodsTypeList(0, 100);

		model.addAttribute("typeList", typeList);
		return "/view/cluster/clusterGoodsAdd";
	}

	/**
	 * 商品添加
	 * */
	@RequestMapping(value = "/view/clusterGoodsAdd.do", method = RequestMethod.POST)
	public String createGoods(GoodsForm goodsForm, HttpServletRequest request,
			@RequestParam("filename1") MultipartFile filename1)
			throws IOException, ControllerException {

		try {
			Goods goods = new Goods();

			BeanUtils.copyProperties(goods, goodsForm);
			ClusterCompany clusterCompany =(ClusterCompany) WebUtils.getSessionAttribute(request, "cluster");
			if(clusterCompany==null)
				return "redirect:/view/toClusterGoodsList.do";
			
			goods.setClusterCompany(clusterCompany);
			goods.setProductCompany(clusterCompany.getCompanyname());
			String filePath = UploadFileUtil.Upload(request, filename1,"cluster/"+clusterCompany.getCompanyname()+"/goods");
			goods.setProductPicture(filePath);
			
			String createTime = DateFormatUtils.format(new Date(),
					"yyyy-MM-dd HH:mm:ss");
			goods.setCreateDate(createTime);
			
			goods.setUpdateTime(createTime);
			
			String productCode = GetFirstLetterUtils.getUpcase(goods
					.getProductType()) + Goods.getProductID();
			goods.setProductCode(productCode);
			goodsService.createGoods(goods);
			

			return "redirect:/view/toClusterGoodsList.do";
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
		}
	}
	
	/*
	 * 商品修改
	 */
	
	@RequestMapping("/view/clusterGoodsModify.do")
	public String clusterGoodsModify(GoodsForm goodsForm,HttpServletRequest request,@RequestParam("filename1")MultipartFile filename1) throws ControllerException{
		Goods goods = new Goods();
		try {
			String specifications = goodsForm.getSpecifications();
			String description = goodsForm.getDescription();
			int commond = goodsForm.getIsCommond();
			int newGood = goodsForm.getIsNew();
			int promotion = goodsForm.getIsPromotion();
			int visible = goodsForm.getIsVisible();
			ClusterCompany clusterCompany = (ClusterCompany)request.getAttribute("cluster");
			BeanUtils.copyProperties(goods, goodsForm);
			
			goods.setSpecifications(specifications);
			goods.setDescription(description);
			goods.setIsCommond(commond);
			goods.setIsNew(newGood);
			goods.setIsPromotion(promotion);
			goods.setIsVisible(visible);
			
			if(filename1.getSize()!=0)
			{
				String filePath =UploadFileUtil.Upload(request, filename1,"cluster/"+clusterCompany.getCompanyname()+"/goods");
				goods.setProductPicture(filePath);
			}
			
			String updateTime=DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss");
			goods.setUpdateTime(updateTime);
			goodsService.modifyGoods(goods);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
			
		} catch (InvocationTargetException e) {
			e.printStackTrace();
			throw new ControllerException("参数不正确");
		}
		return "redirect:/view/toClusterGoodsList.do";
	}

	/*
	 * 删除商品
	 */

	@RequestMapping("/view/deleteClusterGoods.do")
	public String deletGoods(@RequestParam("id") long id) {
		goodsService.removeGoodsByID(id);
		return "redirect:/view/toClusterGoodsList.do";
	}

	/*
	 * 修改商品
	 */
	@RequestMapping(value = "/view/toModifyGoods.do")
	public String toGoodsModify(Model model, @RequestParam("id") int id) {
		Goods goods = goodsService.getGoodsById(id);
		System.out.println(goods.getProductPicture() + "==========");

		ArrayList<GoodsType> goodsType = (ArrayList<GoodsType>) goodsTypeService
				.getGoodsTypeList(0, 100);

		model.addAttribute("goodsType", goodsType);

		model.addAttribute("goods", goods);
		return "/view/cluster/clusterGoodsModify";
	}

	/*
	 * 搜索商品
	 */
	
	@RequestMapping(value="/view/searchClusterGoods.do")
	public String searchClusterGoods(HttpServletRequest request,Model model){
		
		int searchType = Integer.parseInt(request.getParameter("cid")); 
		String keyword = request.getParameter("keyword");
		HttpSession session = request.getSession();
		ClusterCompany clusterCompany = (ClusterCompany)session.getAttribute("cluster");
		String[] paramValues=new String[2] ;
		paramValues[0]=clusterCompany.getId().toString();
		
	    if(searchType!=0){
			paramValues[1]='%'+keyword+'%';
			List<Goods> goodsList = clusterService.getClusterCompanyGoodsList(paramValues, searchType,0, 10);
			
			Long maxSize = (long) clusterService.getClusterCompanyGoodsList(paramValues).size();
			System.out.println("maxsize==="+maxSize);
			model.addAttribute("goodsList", goodsList);
			model.addAttribute("maxSize", maxSize);
			return "/view/cluster/clusterGoodsList";
	    }else{
		  return "redirect:/view/toClusterGoodsList.do";
	    }
	}	
		
	
	/*
	 * 订单管理
	 */

	@RequestMapping("/view/toClusterOrderList.do")
	public String toClusterOrderList(HttpServletRequest request,Model model) {
        
		HttpSession session = request.getSession();
		ClusterCompany clusterCompany =  (ClusterCompany)session.getAttribute("cluster");
	    List<Orders> ordersList = orderService.getClusterCompanyOrdersList(clusterCompany.getId(),0,10);
	    long maxSize = (long) orderService.getClusterCompanyOrdersList(clusterCompany.getId()).size();
	    model.addAttribute("ordersList", ordersList);
	    model.addAttribute("maxSize", maxSize);
		return "/view/cluster/clusterOrderList";
	}

	@RequestMapping("/view/toModifyOrder.do")
	public String toModifyOrder(HttpServletRequest request){
		
		Orders order = null;
		orderService.modifyOrder(order);
		return "/view/cluster/modifyOrders";
	}
	
	@RequestMapping("/view/deleteOrder.do")
	public String deleteOrder(HttpServletRequest request){
		
		String orderId = request.getParameter("orderId");
		orderService.deleteRelateOrder(orderId);
		return "redirect:/view/toClusterOrderList.do";
	}
	
	@RequestMapping("/view/toOrderDetails.do")
    public String toOrderDetails(HttpServletRequest request,Model model){
		
		String id = request.getParameter("id");
		HttpSession session = request.getSession();
		Orders order = orderService.getOrder(Long.parseLong(id));
		model.addAttribute("order", order);
		return "/view/cluster/OrderDetails";
	}
	
	@RequestMapping("/view/searchOrderByOrderId.do")
	public String searchOrderByOrderId(HttpServletRequest request,Model model){
		
		String orderId = request.getParameter("orderId");
		List<Orders> ordersList = orderService.getOrderByOrderId(orderId,0,10);
	    long maxSize = orderService.getOrderByOrderId(orderId).size();
	    model.addAttribute("ordersList", ordersList);
	    model.addAttribute("maxSize", maxSize);
	    
	    
	    return "/view/cluster/clusterOrderList";
	    
	}
	
	@RequestMapping("/view/searchOrderByStat.do")
	public String searchOrderByStat(HttpServletRequest request,Model model){
		
		String orderStat = request.getParameter("orderStat");
		ClusterCompany clusterCompany = (ClusterCompany)WebUtils.getSessionAttribute(request, "cluster");
		String[] paramValues = new String[2];
		paramValues[0]=clusterCompany.getId().toString();
		
		if(orderStat == "0"){
			return "redirect:/view/toClusterOrderList.do";
		}else{
			paramValues[1]=orderStat;
			List<Orders> ordersList = orderService.getOrderByStat(paramValues,0,10);
		    long maxSize = orderService.getOrderByStat(paramValues).size();
		    model.addAttribute("ordersList", ordersList);
		    model.addAttribute("maxSize", maxSize);
		}

	    return "/view/cluster/clusterOrderList";
	}
	
	@RequestMapping("/view/searchOrderByDate.do")
	public String searchOrderByDate(HttpServletRequest request,Model model){
		
	    String date = request.getParameter("date");
	    ClusterCompany clusterCompany = (ClusterCompany)WebUtils.getSessionAttribute(request, "cluster");
		String[] paramValues = new String[2];
		paramValues[0]=clusterCompany.getId().toString();
		
		if(date == "0"){
			return "redirect:/view/toClusterOrderList.do";
		}else{
			paramValues[1]=date;
			List<Orders> ordersList = orderService.getOrderByDate(paramValues,0,10);
		    long maxSize = orderService.getOrderByDate(paramValues).size();
		    model.addAttribute("ordersList", ordersList);
		    model.addAttribute("maxSize", maxSize);
		}

	    return "/view/cluster/clusterOrderList";
	    
	    
	}
	/*
	 * 连锁经营店管理
	 */
	@RequestMapping("/view/toClusterCompanyList.do")
	public String toCompanyList(HttpServletRequest request, Model model) {
		return "/view/cluster/clusterCompanyList";

	}

	@RequestMapping("/view/toChainCompanyAdd.do")
	public String toChainCompanyAdd(Model model,HttpServletRequest request) {
		
      ClusterCompany clusterCompany = (ClusterCompany) WebUtils.getSessionAttribute(request, "cluster");
		
		return "/view/cluster/clusterChainCompanyAdd";

	}

	@RequestMapping("/view/chainCompanyAdd.do")
	public String ChainCompanyAdd(HttpServletRequest request,ChainForm chainForm,@RequestParam("fileName1")MultipartFile fileName1) {
		ChainCompany chainCompany = new ChainCompany();
		ClusterCompany clusterCompany = (ClusterCompany) WebUtils.getSessionAttribute(request, "cluster");
		try {
			BeanUtils.copyProperties(chainCompany, chainForm);
			String filePath = UploadFileUtil.Upload(request, fileName1,"cluster/chain");
			chainCompany.setCertificatesUpload(filePath);
			chainCompany.setClusterCompany(clusterCompany);
            
			Date createDate = new Date();
			chainCompany.setCreateDate(createDate);
			chainCompanyService.createChainCompany(chainCompany);
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return "redirect:/view/toChainCompanyList.do";

	}

	@RequestMapping("/view/toChainCompanyList.do")
	public String ChainCompanyList(HttpServletRequest request, Model model) {
		
		ClusterCompany clusterCompany = (ClusterCompany) WebUtils.getSessionAttribute(request, "cluster");
		
		if(clusterCompany==null) return "/view/login";

		List<ChainCompany> chainList = new ArrayList<ChainCompany>();
		chainList = chainCompanyService.getChainCompanyListByCluster(clusterCompany.getId());
		if(chainList.size()==0) return "/view/cluster/chainCompanyList";
		long maxSize = chainCompanyService.getChainCompanyListByCluster(clusterCompany.getId()).size();
		model.addAttribute("chainList", chainList);
		model.addAttribute("maxSize", maxSize);
		return "/view/cluster/chainCompanyList";

	}
	
	@RequestMapping("/view/searchChainByName.do")
	public String searchChainByName(HttpServletRequest request,Model model){
		
		String keyword = request.getParameter("keyword");
		ClusterCompany clusterCompany = (ClusterCompany)WebUtils.getSessionAttribute(request, "cluster");
		
		if(clusterCompany==null) {System.out.println("clusterCompany============");return "view/login";}
		else
		System.out.println("clusterCompany============"+clusterCompany.getId());
		
		String[] paramValues=new String[2];
	    paramValues[0]=clusterCompany.getId().toString();
	    paramValues[1]='%'+keyword+'%';
		List<ChainCompany> chainList = chainCompanyService.searchChainByName(paramValues,0,10);
		long maxSize = chainCompanyService.searchChainByName(paramValues).size();
		model.addAttribute("chainList", chainList);
		model.addAttribute("maxSize", maxSize);
		return "/view/cluster/chainCompanyList";

	}
	
	//*****圣茵后台集群企业管理
	@RequestMapping(value = "/toclusterList.do")
	public String toAllianceList(Model model,HttpServletRequest request) {
		
       int offset = 0;
       try{
    	   offset = Integer.valueOf(request.getParameter("pager.offset"));
    	   

		} catch (Exception ex) {
			System.out.println("初始化页数.......");
		}
       List<ClusterCompany> companyList = null;
		
	    companyList = clusterService.getCompanyList(offset,10);    	  
		
	    Long maxSize = clusterService.getTotal();
	    System.out.println("================maxSize============================="+maxSize);
		model.addAttribute("companyList", companyList);
		model.addAttribute("maxSize",maxSize);
		return "/admin/cluster/clusterList";
	}
	
	@RequestMapping(value="/toclusterQuery.do")
    public String toclusterQuery(Model model,@RequestParam ("status") String status,HttpServletRequest request){
    	int offset=0;
    	Long maxSize=(long) 0;
    	List<ClusterCompany> companyList = new ArrayList<ClusterCompany>();
    
    	
    	try{
    		offset = Integer.valueOf(request.getParameter("pager.offset"));
    	} catch (Exception ex) {
			
    		
    	}
    	if(status.equals("0"))
    	{ companyList = clusterService.getCompany(0, offset, 10);
    	   maxSize = (long) clusterService.getCompany(0).size();
    	   
    	}
    	if(status.equals("1"))
    	{ companyList = clusterService.getCompany(1, offset, 10);
    	 maxSize = (long) clusterService.getCompany(1).size();
    	 
    	}
    	
    	if(status.equals("2"))
    	{  companyList =  clusterService.getCompany(2, offset, 10);
    	   maxSize = (long) clusterService.getCompany(2).size();
    	  
    	}
    	
    	model.addAttribute("status", status);
    	model.addAttribute("maxSize", maxSize);
    	model.addAttribute("companyList", companyList);
    	return "/admin/cluster/clusterQuery";
    }
	
	  @RequestMapping("/searchClusterByName.do")
	    public String searchClusterByName(HttpServletRequest request,Model model){
	    	
	    	String keyword = request.getParameter("keyword");
	    	keyword = '%'+keyword+'%';
	    	List<ClusterCompany> companyList = clusterService.getCompanyListByName(keyword,0,10);
	    	long maxSize = clusterService.getCompanyListByName(keyword).size();
	    	
	    	model.addAttribute("maxSize", maxSize);
	    	model.addAttribute("companyList", companyList);
	    	
	    	return "/admin/cluster/clusterList";
	    }

}
